package org.zoomdev.zoom.lock.modules;

import org.zoomdev.zoom.common.exceptions.CasException;
import org.zoomdev.zoom.lock.Executor;
import org.zoomdev.zoom.lock.LockExecutor;

import java.util.concurrent.ConcurrentHashMap;

public final class CasLockExecutor implements LockExecutor {

    private final ConcurrentHashMap<String, Boolean> pool;
    private final String message;

    public CasLockExecutor(ConcurrentHashMap<String, Boolean> pool, String message) {
        this.pool = pool;
        this.message = message;
    }

    @Override
    public Object execute(String key, Executor executor) throws Throwable {
        if (pool.putIfAbsent(key, Boolean.TRUE) != null) {
            throw new CasException(message);
        }
        try {
            return executor.execute();
        } finally {
            pool.remove(key);
        }
    }
}
